package com.ruoyi.security.util;

import com.google.common.collect.Lists;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author yeoman
 * @date 2025/1/20 21:25
 * @description
 */
public class DateUtil extends org.apache.commons.lang3.time.DateUtils {

    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    private static final String[] PARSE_PATTERNS = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM",
            "yy-MM-dd", "yyyy年MM月dd日", "yy年MM月dd日", "yy/MM/dd",
    };

    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), PARSE_PATTERNS);
        } catch (ParseException e) {
            return null;
        }
    }

    public static String parseDateToStr(Date date) {
        return new SimpleDateFormat(YYYY_MM_DD).format(date);
    }

    public static String parseDateToStr(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 获取非周末日期列表
     * @param startDateStr 开始日期
     * @param endDateStr 结束日期
     * @return 日期列表
     */
    public static List<String> getNonWeekendDateList(String startDateStr, String endDateStr) {
        List<String> dateRangeList = Lists.newArrayList();
        Calendar calendar = Calendar.getInstance();
        Date startDate;
        Date endDate;
        try {
            startDate = parseDate(startDateStr, PARSE_PATTERNS);
            endDate = parseDate(endDateStr, PARSE_PATTERNS);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        calendar.setTime(startDate);
        if (Calendar.SATURDAY != calendar.get(Calendar.DAY_OF_WEEK) && Calendar.SUNDAY != calendar.get(Calendar.DAY_OF_WEEK)) {
            dateRangeList.add(startDateStr);
        }
        while (true) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date nextDay = calendar.getTime();
            if (nextDay.after(endDate)) {
                break;
            }else {
                if (Calendar.SATURDAY != calendar.get(Calendar.DAY_OF_WEEK) && Calendar.SUNDAY != calendar.get(Calendar.DAY_OF_WEEK)) {
                    dateRangeList.add(new SimpleDateFormat(YYYY_MM_DD).format(nextDay));
                }
            }
        }
       return dateRangeList;
    }

}
